<template>
  <div class="user-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
          <el-button type="primary" @click="showAddDialog">
            <el-icon><Plus /></el-icon>
            添加用户
          </el-button>
        </div>
      </template>
      
      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索用户名或邮箱"
          clearable
          @input="handleSearch"
          style="width: 300px; margin-right: 10px;"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
      
      <!-- 用户表格 -->
      <el-table
        v-loading="loading"
        :data="users"
        style="width: 100%; margin-top: 20px;"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="realName" label="真实姓名" />
        <el-table-column prop="phone" label="电话" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" @click="editUser(scope.row)">编辑</el-button>
            <el-button
              size="small"
              type="danger"
              @click="deleteUser(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 添加/编辑用户对话框 -->
    <el-dialog
      v-model="showDialog"
      :title="isEdit ? '编辑用户' : '添加用户'"
      width="500px"
      @close="resetForm"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userRules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="userForm.username"
            :disabled="isEdit"
            placeholder="请输入用户名"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="密码" prop="password" v-if="!isEdit">
          <el-input
            v-model="userForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
            clearable
          />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="userForm.email"
            placeholder="请输入邮箱"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="真实姓名" prop="realName">
          <el-input
            v-model="userForm.realName"
            placeholder="请输入真实姓名"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="电话" prop="phone">
          <el-input
            v-model="userForm.phone"
            placeholder="请输入电话"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="状态" prop="status" v-if="isEdit">
          <el-select v-model="userForm.status" placeholder="请选择状态">
            <el-option label="活跃" value="ACTIVE" />
            <el-option label="非活跃" value="INACTIVE" />
            <el-option label="锁定" value="LOCKED" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
          {{ isEdit ? '更新' : '添加' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'
import { userApi } from '@/api/user'

export default {
  name: 'UserManagement',
  components: {
    Plus,
    Search
  },
  setup() {
    const loading = ref(false)
    const submitLoading = ref(false)
    const showDialog = ref(false)
    const isEdit = ref(false)
    const searchKeyword = ref('')
    const users = ref([])
    const selectedUsers = ref([])
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    
    const userFormRef = ref()
    const userForm = reactive({
      id: null,
      username: '',
      password: '',
      email: '',
      realName: '',
      phone: '',
      status: 'ACTIVE'
    })
    
    const userRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 50, message: '用户名长度在3-50个字符', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '密码长度至少6位', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
      ]
    }
    
    const loadUsers = async () => {
      loading.value = true
      try {
        const response = await userApi.getUsers()
        users.value = response.data.data || []
        total.value = users.value.length
      } catch (error) {
        ElMessage.error('加载用户列表失败')
      } finally {
        loading.value = false
      }
    }
    
    const handleSearch = () => {
      // 实现搜索逻辑
      loadUsers()
    }
    
    const handleSelectionChange = (selection) => {
      selectedUsers.value = selection
    }
    
    const handleSizeChange = (size) => {
      pageSize.value = size
      loadUsers()
    }
    
    const handleCurrentChange = (page) => {
      currentPage.value = page
      loadUsers()
    }
    
    const showAddDialog = () => {
      isEdit.value = false
      showDialog.value = true
      resetForm()
    }
    
    const editUser = (user) => {
      isEdit.value = true
      showDialog.value = true
      Object.assign(userForm, user)
    }
    
    const deleteUser = async (user) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除用户 "${user.username}" 吗？`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        await userApi.deleteUser(user.id)
        ElMessage.success('删除成功')
        loadUsers()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }
    
    const handleSubmit = async () => {
      if (!userFormRef.value) return
      
      await userFormRef.value.validate(async (valid) => {
        if (valid) {
          submitLoading.value = true
          try {
            if (isEdit.value) {
              await userApi.updateUser(userForm.id, userForm)
              ElMessage.success('更新成功')
            } else {
              await userApi.createUser(userForm)
              ElMessage.success('添加成功')
            }
            showDialog.value = false
            loadUsers()
          } catch (error) {
            ElMessage.error(isEdit.value ? '更新失败' : '添加失败')
          } finally {
            submitLoading.value = false
          }
        }
      })
    }
    
    const resetForm = () => {
      if (userFormRef.value) {
        userFormRef.value.resetFields()
      }
      Object.assign(userForm, {
        id: null,
        username: '',
        password: '',
        email: '',
        realName: '',
        phone: '',
        status: 'ACTIVE'
      })
    }
    
    const getStatusType = (status) => {
      switch (status) {
        case 'ACTIVE': return 'success'
        case 'INACTIVE': return 'info'
        case 'LOCKED': return 'danger'
        default: return 'info'
      }
    }
    
    const getStatusText = (status) => {
      switch (status) {
        case 'ACTIVE': return '活跃'
        case 'INACTIVE': return '非活跃'
        case 'LOCKED': return '锁定'
        default: return '未知'
      }
    }
    
    onMounted(() => {
      loadUsers()
    })
    
    return {
      loading,
      submitLoading,
      showDialog,
      isEdit,
      searchKeyword,
      users,
      selectedUsers,
      currentPage,
      pageSize,
      total,
      userFormRef,
      userForm,
      userRules,
      loadUsers,
      handleSearch,
      handleSelectionChange,
      handleSizeChange,
      handleCurrentChange,
      showAddDialog,
      editUser,
      deleteUser,
      handleSubmit,
      resetForm,
      getStatusType,
      getStatusText
    }
  }
}
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-bar {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>


